#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int pipefd[2] = {0};
    
    pipe(pipefd);
    //printf("%d, %d\n",pipefd[0], pipefd[1]);   // pipefd[0] = 3(read), pipefd[1] = 4(write)
    
    pid_t id = fork();
    if(id < 0){
        perror("fork error\n");
        return 1;
    }

    if(id == 0){  //child read
        close(pipefd[1]);  //关闭标准输出
        char buffer[64];   //缓冲区
        while(1){
            ssize_t str = read(pipefd[0], buffer, sizeof(buffer) - 1);
            if(str > 0) 
                buffer[str] = 0;
            printf("child get message : %s\n", buffer);
        }
    }
    
    else{    //father write
        close(pipefd[0]);   //关闭标准输入
        const char * s = "i am runing\n";

        while(1){
            write(pipefd[1], s, strlen(s));
            sleep(1);    //每一秒发送一条消息
        }
    }
    
    return 0;
}

